package app.interceptor;

import javax.servlet.http.HttpServletRequest;

import app.annotations.Public;
import app.controllers.IndexController;
import app.controllers.LoginController;
import app.session.UserSession;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;

/**
 * Intercepta verificando o login do usuario.
 * Se nao estiver logado redireciona para a pagina de login.
 * Se estiver logado, segue o fluxo
 * 
 * @author Douglas Fernandes
 * @since 24/11/2013
 */
@Intercepts
public class LoginInterceptor implements Interceptor {

    private Result result;
    private UserSession userSession;
    private HttpServletRequest request;

    public LoginInterceptor(Result result, UserSession userSession, HttpServletRequest request) {
        this.result = result;
        this.userSession = userSession;
        this.request = request;
    }

    public boolean accepts(ResourceMethod method) {
    	
        return !(method.getMethod().isAnnotationPresent(Public.class) ||
            method.getResource().getType().isAnnotationPresent(Public.class));
    }

    public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) {
    	
//    	if(!request.getHeader("Ajax").equals("ajax")){
//            this.result.redirectTo(IndexController.class).error();
//    	}
    
        if (userSession.isLogged()) {
            stack.next(method, resourceInstance);
        } else {
            result.redirectTo(LoginController.class).login();
        }
    }
}